<?php

namespace App\Admin\Controllers;

use App\Models\Product;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ProductsController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Product(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('description');
            $grid->column('on_sale')->display(function ($value) {
                return $value ? '是' : '否';
            });
            $grid->column('price');
            $grid->column('rating');
            $grid->column('sold_count');
            $grid->column('review_count');

            $grid->column('created_at');

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(Product::with('skus'), function (Form $form) {
            $form->display('id');
            $form->text('title');
            $form->textarea('description');
            $form->image('image')->removable(false);
            $form->radio('on_sale')->options([0 => '否', 1 => '是'])->default(1);

            $form->hasMany('skus', 'SKU列表', function (Form\NestedForm $form) {
                $form->text('title', 'SKU 名称')->rules('required');
                $form->textarea('description', 'SKU 描述')->rules('required');
                $form->decimal('price', '单价')->rules('required|numeric|min:0.01');
                $form->number('stock', '剩余库存')->rules('required|integer|min:0');
            });
            $form->saving(function (Form $form) {
                $min_price = collect($form->input('skus'))->where(Form::REMOVE_FLAG_NAME, 0)->min('price') ?: 0;
                $form->input('price', $min_price);
            });
        });
    }
}
